package com.android.thelastnoet;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.MenuItemCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.android.thelastnoet.adapter.NoteAdapter;
import com.android.thelastnoet.bean.Note;
import com.android.thelastnoet.customView.RefreshableView;
import com.android.thelastnoet.db.NoteMapper;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import static android.os.Build.VERSION_CODES.M;

public class NoteListActivity extends AppCompatActivity {

    FloatingActionButton fab;
    Toolbar toolbar;
    CollapsingToolbarLayout ctl;
    SearchView searchView;
    private String groupName = "";

    NoteMapper noteMapper = new NoteMapper(this);

    RecyclerView recyclerView;
    List<Note> noteList = new ArrayList<>();
    NoteAdapter noteAdapter;

    @SuppressLint("CommitPrefEdits")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_list);

        toolbar = findViewById(R.id.toolbar_main);
        ctl = findViewById(R.id.collapsing_toolbarLayout);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NoteListActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

        groupName = getIntent().getStringExtra("groupName");
        ctl.setTitle(groupName);
        Log.d("noteList",groupName);

        fab = findViewById(R.id.main_add_fab);
        fab.setOnClickListener(v -> {
            /*携带分组及状态信息 跳转至编辑页面*/
            Intent intent = new Intent(NoteListActivity.this, EditActivity.class);
            intent.putExtra("groupName", this.groupName);
            intent.putExtra("state", "new");
            startActivity(intent);
        });

        /*初次启动 获得数据库中便签数据 用于适配器数据渲染*/
        refreshNotes();
        /*便签数据适配*/
        setNoteData();

    }


    /*根据组名groupName 刷新数据noteList对象*/
    private void refreshNotes() {
        noteList = noteMapper.getNotesByGroup(groupName);
    }

    /*设置便签显示列表*/
    private void setNoteData() {
        /*设置便签列表适配器*/
        recyclerView = findViewById(R.id.recycle_view);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        noteAdapter = new NoteAdapter(noteList, this);
        recyclerView.setAdapter(noteAdapter);

        /*设置单条便签点击事件*/
        noteAdapter.setOnItemClickListener((view, note) -> {
            Intent intent = new Intent(NoteListActivity.this, EditActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("Note", note);
            intent.putExtra("data", bundle);
            intent.putExtra("state", "edit");
            Log.d("Main", note.getGroupName());
            startActivity(intent);
        });
        noteAdapter.setOnItemLongClickListener((view, note) -> {

        });
    }

    /*刷新 adapter中的数据*/
    private void refreshAdapter(List<Note> noteList) {
        //这里应该是输入一个组名 刷新这个组名下的 notes
        noteAdapter.setNoteList(noteList);
    }

    /*设置标题栏下拉菜单*/
    @RequiresApi(M)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_bar_menu, menu);

        MenuItem searchItem = menu.findItem(R.id.search);

        searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        searchView.setSubmitButtonEnabled(false);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }
            @Override
            public boolean onQueryTextChange(String s) {
                Log.d("Main", s);
                if (TextUtils.isEmpty(s)) {
                    refreshNotes();
                } else {
                    noteList = filter(noteList, s);
                }
                refreshAdapter(noteList);
                return true;
            }
        });
        searchView.setOnCloseListener(() -> {
            refreshNotes();
            refreshAdapter(noteList);
            fab.setVisibility(View.VISIBLE);
            return false;
        });

        return true;
    }

    /*menu菜单点击事件监听*/
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {

            case R.id.list_mode:

                Toast.makeText(this, "列表模式", Toast.LENGTH_SHORT).show();
                break;
            case R.id.grid_mode:
                Toast.makeText(this, "宫格模式", Toast.LENGTH_SHORT).show();
                break;
            case R.id.setting:
                Intent intent = new Intent(this, SettingActivity.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /*
     *利用反射机制调用MenuBuilder的setOptionalIconsVisible方法设置mOptionalIconsVisible为true
     * 给菜单设置图标时才可见 让菜单同时显示图标和文字
     * */
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menu != null) {
            if (menu.getClass().getSimpleName().equalsIgnoreCase("MenuBuilder")) {
                try {
                    Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    method.setAccessible(true);
                    method.invoke(menu, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    /*过滤器*/
    private List<Note> filter(List<Note> noteList, String text) {
        List<Note> filterString = new ArrayList<>();
        for (Note note : noteList) {
            if (note.getContent().contains(text)
                    || note.getTitle().contains(text)) {
                filterString.add(note);
            }
        }
        return filterString;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Intent intent = new Intent(NoteListActivity.this, MainActivity.class);
        startActivity(intent);
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
/*        if (getIntent()!=null) {
            Intent intent = getIntent();
            groupName = intent.getStringExtra("groupName");
            Log.d("main",groupName+"");
        }*/
        refreshNotes();
        refreshAdapter(noteList);
    }
}